#!/bin/bash

logfile="./.image_install_$(date '+%Y%m%d%H%M%S').log"

now() {
    date '+%Y-%m-%d %H:%M:%S'
}

do_log() {
    echo "$(now) [$1] $2" >> "${logfile}"
}

log_info() {
    do_log "I" "$1"
}

log_error() {
    do_log "E" "$1"
}

error_msg() {
    echo -e "${ERROR} ${1}"
    exit 1
}

genSn() {
	mv ./as-watch /usr/sbin/
	mv ./as-watch.service /usr/lib/systemd/system/
# Gen SN
    PPChannelID=101574
    DeviceBindUrl=""
    RID=$(cat /dev/urandom | head -c 8 | hexdump -ve '1/1 "%.2x"' | tr '[:lower:]' '[:upper:]')
    SN_PREFIX=PA02
    SN="${SN_PREFIX}${RID}"
    qrcode_content="${SN}"
    if [ -n "${PPChannelID}" ];then
        qrcode_content="${SN}_PS${PPChannelID}"
        echo "${PPChannelID}" > ${DIR_INSTALL}/etc/pai_channel
    fi
    #SN="PA00TESTACDC721F0000"
    log_info "SN: ${SN}"
    echo "$SN" > ${DIR_INSTALL}/etc/device_sn
    echo "SN: $SN" > ${DIR_INSTALL}/etc/issue
    /usr/bin/qrencode -m 1 -t ANSI "${qrcode_content}" >> ${DIR_INSTALL}/etc/issue 2>>"${logfile}"
    cat ${DIR_INSTALL}/etc/issue >> "${logfile}"
    /usr/bin/qrencode  -m 1 -s 9 -t PNG "${qrcode_content}" -o /boot/device_sn.png 2>>"${logfile}"
    echo "$SN" > /boot/boxsn.txt

    # flag string, DO NOT CHANGE
    echo "generate sn qrcode succeed"

    sleep 3

    if ! ln -f -s /usr/lib/systemd/system/as-watch.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/as-watch.service";then
        log_error "enable as-watch service failed"
        error_msg "enable as-watch service failed"
    fi

    #ln -f -s /usr/lib/systemd/system/ppboxhttp-watch.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/ppboxhttp-watch.service"

    ln -f -s /usr/lib/systemd/system/scan-pppconf.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/scan-pppconf.service"
    ln -f -s /usr/lib/systemd/system/pai-networkd.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/pai-networkd.service"
    ln -f -s /usr/lib/systemd/system/pi-net.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/pi-net.service"

    ln -f -s /usr/lib/systemd/system/ppboxhttp.service "${DIR_INSTALL}/etc/systemd/system/multi-user.target.wants/ppboxhttp.service"
}

genSn
